from rest_framework.response import Response
from rest_framework.status import HTTP_401_UNAUTHORIZED

def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'id':user.id,
        'username':user.username,
        'mobile':user.mobile,
        'token':token,
        'avatar':user.avatar
    }



from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication, jwt_decode_handler
from rest_framework_jwt.utils import jwt_decode_handler
import jwt
class JwtAuthentication(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        try:
            token = request.META.get('HTTP_Authorization'.upper())[4:]
        except:
            return Response(status=HTTP_401_UNAUTHORIZED)
        try:
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('过期了')
        except jwt.DecodeError:
            raise AuthenticationFailed('解码错误')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('不合法的token')
        user = payload
        return (user,token)

